package integral

import (
	"context"
	"strings"
	"time"

	"mall/common/globalkey"
	"mall/common/modelx"
	"mall/common/utils/pointy"
	"mall/service/user/model"
	"mall/service/user/rpc/internal/svc"
	"mall/service/user/rpc/types/user"

	"github.com/zeromicro/go-zero/core/logx"
)

type BackendGetIntegralTaskLogListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewBackendGetIntegralTaskLogListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *BackendGetIntegralTaskLogListLogic {
	return &BackendGetIntegralTaskLogListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *BackendGetIntegralTaskLogListLogic) BackendGetIntegralTaskLogList(in *user.IntegralTaskLogListReq) (*user.IntegralTaskLogListResp, error) {
	logx.Infof("BackendGetIntegralTaskLogList req:%+v", in)
	//var orderBys []string
	//if len(in.OrderBy) > 0 {
	//	for _, orderBy := range in.OrderBy {
	//		order := " ASC"
	//		if orderBy.Order == "1" {
	//			order = " DESC"
	//		}
	//		if orderBy.Field == "id" {
	//			orderBys = append(orderBys, model.ForumPostColumns.PostID+order)
	//		}
	//		if orderBy.Field == "sort" {
	//			orderBys = append(orderBys, model.ForumPostColumns.Sort+order)
	//		}
	//		if orderBy.Field == "createdAt" {
	//			orderBys = append(orderBys, model.ForumPostColumns.PostDate+order)
	//		}
	//	}
	//}

	//var stati string
	//var postType string
	//if len(in.FilterBy) > 0 {
	//	for _, filterBy := range in.FilterBy {
	//		switch filterBy.Field {
	//		case "status":
	//			stati = filterBy.In
	//		case "type":
	//			postType = filterBy.In
	//		}
	//	}
	//}

	var filter = make(map[string]map[string][]any)
	if in.Ids != nil && len(*in.Ids) > 0 {
		if ids := modelx.UniqueInterfaces(*in.Ids, 64); len(ids) > 0 {
			filter[model.UserTaskLogColumns.TaskID] = map[string][]any{
				"in": ids,
			}
		}
	}
	if in.UserId != nil && *in.UserId > 0 {
		filter[model.UserTaskLogColumns.UserID] = map[string][]any{
			"equalTo": {*in.UserId},
		}
	}

	now := time.Now()
	createdAtMap := make(map[string][]any)
	var startTimeIn []any
	var endTimeIn []any
	if in.WithCycle != nil && *in.WithCycle > 0 {
		switch *in.WithCycle {
		case globalkey.UserLogTypeToday:
			//今天
			//格式化后: 2025-03-01 00:00:00 ==> 2025-03-01 23:59:59
			startOfDay := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location())
			endOfDay := startOfDay.Add(23 * time.Hour).Add(59 * time.Minute).Add(59 * time.Second)
			startTimeIn = append(startTimeIn, startOfDay)
			endTimeIn = append(endTimeIn, endOfDay)
		case globalkey.UserLogTypeWeek:
			//本周
			//格式化后: 2025-02-24 00:00:00 ==> 2025-03-02 23:59:59
			startTime := now.AddDate(0, 0, -int(now.Weekday())+1)
			startOfWeek := time.Date(startTime.Year(), startTime.Month(), startTime.Day(), 0, 0, 0, 0, startTime.Location())
			endOfWeek := startOfWeek.AddDate(0, 0, 6).Add(23*time.Hour + 59*time.Minute + 59*time.Second)
			startTimeIn = append(startTimeIn, startOfWeek)
			endTimeIn = append(endTimeIn, endOfWeek)
		case globalkey.UserLogTypeMonth:
			//本月
			//格式化后: 2025-02-01 00:00:00 ==> 2025-02-28 23:59:59
			year, month, _ := now.Date()
			location := now.Location()
			var nextMonth time.Time
			if month == 12 {
				nextMonth = time.Date(year+1, 1, 1, 0, 0, 0, 0, location)
			} else {
				nextMonth = time.Date(year, month+1, 1, 0, 0, 0, 0, location)
			}
			startOfMonth := time.Date(year, month, 1, 0, 0, 0, 0, location)
			endOfMonth := nextMonth.Add(-time.Second)
			startTimeIn = append(startTimeIn, startOfMonth)
			endTimeIn = append(endTimeIn, endOfMonth)
		case globalkey.UserLogTypeWithinSevenDays:
			//七天内
			startOfDay := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location()).Add(-7 * 24 * time.Hour)
			endOfDay := time.Now()
			startTimeIn = append(startTimeIn, startOfDay)
			endTimeIn = append(endTimeIn, endOfDay)
		case globalkey.UserLogTypeWithinThirtyDays:
			//三十天内
			startOfDay := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location()).Add(-30 * 24 * time.Hour)
			endOfDay := time.Now()
			startTimeIn = append(startTimeIn, startOfDay)
			endTimeIn = append(endTimeIn, endOfDay)
		}
	} else if in.StartTime != nil && len(strings.TrimSpace(*in.StartTime)) > 0 {
		if startTime, err := modelx.ParseLocalDate(strings.TrimSpace(*in.StartTime)); err == nil {
			startTimeIn = append(startTimeIn, startTime)
		}
		if in.EndTime != nil && len(strings.TrimSpace(*in.EndTime)) > 0 {
			if endTime, err := modelx.ParseLocalDate(strings.TrimSpace(*in.EndTime)); err == nil {
				endTimeIn = append(endTimeIn, endTime)
			}
		} else {
			endTimeIn = append(endTimeIn, now)
		}
	}
	if len(startTimeIn) > 0 {
		createdAtMap["moreThanOrEqualTo"] = startTimeIn
	}
	if len(endTimeIn) > 0 {
		createdAtMap["lessThan"] = endTimeIn
	}
	if len(createdAtMap) > 0 {
		filter[model.UserTaskLogColumns.UpdatedAt] = createdAtMap
	}
	res, _, err := l.svcCtx.CurrentUser.GetTaskLogList(l.ctx, model.M{}, -1, filter)
	if err != nil {
		return nil, err
	}
	var list []*user.IntegralTaskLogInfo
	if len(res) > 0 {
		for _, v := range res {
			list = append(list, &user.IntegralTaskLogInfo{
				Id:        pointy.GetPointer(v.ID),
				UserId:    pointy.GetPointer(v.UserID),
				TaskId:    pointy.GetPointer(v.TaskID),
				TaskName:  pointy.GetPointer(v.TaskName),
				TaskSlug:  pointy.GetPointer(v.TaskSlug),
				Gems:      pointy.GetPointer(uint64(v.Gems)),
				Growth:    pointy.GetPointer(uint64(v.Growth)),
				Integrals: pointy.GetPointer(uint64(v.Integrals)),
				Status:    pointy.GetPointer(uint32(v.Status)),
				CreatedAt: pointy.GetPointer(modelx.FormatTime(v.CreatedAt, "")),
				UpdatedAt: pointy.GetPointer(modelx.FormatTime(v.UpdatedAt, "")),
			})
		}
	}

	return &user.IntegralTaskLogListResp{
		Total: uint64(len(list)),
		List:  list,
	}, nil
}
